package com.suyx.job.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.suyx.job.dao.AppRepository;
import com.suyx.job.entity.AppInfo;
import com.suyx.job.entity.Page;
import com.suyx.job.service.IAppService;
import com.suyx.job.service.base.impl.MyServiceImpl;

import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: lanyanhua
 * @Date: 2018/10/31 0031 10:03
 * @Description:
 */
@Slf4j
@Service
public class AppServiceImpl extends MyServiceImpl<AppInfo,Integer> implements IAppService {

    private AppRepository deviceRepository;

    @Autowired
    public AppServiceImpl(AppRepository deviceRepository) {
        super(deviceRepository);
        this.deviceRepository = deviceRepository;
    }

    @Override
    public Page findAppInfoPage(AppInfo appInfo, int page, Integer limit) {
        return new Page(
        		deviceRepository.findAll((Root<AppInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
                    List<Predicate> predicates = new ArrayList<>();
                    if(!StringUtils.isEmpty(appInfo.getAppName())){
                        predicates.add(cb.like(root.get("appName").as(String.class), "%"+appInfo.getAppName() + "%"));
                    }
                    if(!StringUtils.isEmpty(appInfo.getAppType())){
                        predicates.add(cb.equal(root.get("appType").as(String.class), appInfo.getAppType()));
                    }
                    if(!StringUtils.isEmpty(appInfo.getAppCode())){
                        predicates.add(cb.equal(root.get("appCode").as(String.class), appInfo.getAppCode()));
                    }
                    return  query.where(predicates.toArray(new Predicate[0])).getRestriction();
                }, PageRequest.of(page,limit)));
    }
}
